//
//  KLMHomeSettingController.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/11.
//

import UIKit

class KLMHomeSettingController: KLMBaseHomeTableController {
    
    var homeInfo: KLMHomeInfo?
    var homeUsers: [KLMHomeUser]? {
        didSet {
            if let homeUsers = homeUsers {
                if let user = homeUsers.first(where: { $0.userId == currentUser.id}) {
                    currentHomeUser = user
                    // 拥有者、管理员才有权限
                    canOperateHome = user.userRoleType == .Owner || user.userRoleType == .admin
                }
            }
        }
    }
    /// 当前登录用户信息
    let currentUser: KLMUser.KLMUserData.KLMUserInfo = {
        KLMUser.getUserInfo()!
    }()
    var currentUserRoleType: HomeMemberRoleType = .user
    var currentHomeUser: KLMHomeUser?
    let homeId: Int
    /// 能否改名称、管理家庭、添加成员
    var canOperateHome: Bool = false
    
    init(homeId: Int) {
        self.homeId = homeId
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(refreshUsers), name: .homeMemberChanged, object: nil)
        loadData()
    }
    
    override func loadDataRefreshUI() {
        super.loadDataRefreshUI()
        loadData()
    }
    
    func loadData() {
        loadHomeInfo(homeId: homeId) { infoData in
            self.homeItems = [KLMHomeItem.homeSettingHeaderItems(info: infoData)]
            self.tableView.reloadData()
            
            self.loadHomeUsers(homeId: self.homeId) { homeUsers in
                
                self.endHeaderRefresh()
                
                guard self.currentHomeUser != nil else {
                    SVProgressHUD.showInfo(withStatus: "家庭信息已更新，请返回查看")
                    NotificationCenter.post(.homeInfoChanged)
                    return
                }
                
                var users = KLMHomeItem.homeSettingMemberItems(users: homeUsers)
                if self.canOperateHome {
                    self.homeItems = [KLMHomeItem.homeSettingHeaderItems(info: infoData, canEdit: true)]
                    users.append(KLMHomeItem(type: .tap, title: "添加成员", titleColor: appMainThemeColor, showLine: true, actionType: .addMember))
                }
                
                self.homeItems.append([users])
                self.homeItems.append([KLMHomeItem.homeSettingFooterItems(currentUserType: self.currentHomeUser!.userRoleType)])
                self.tableView.reloadData()
            }
        }
    }
    /// 刷新成员列表
    @objc func refreshUsers() {
        if homeItems.count > 2 {
            let index = homeItems[1].count - 1
            loadHomeUsers(homeId: homeId) { homeUsers in
                var users = KLMHomeItem.homeSettingMemberItems(users: homeUsers)
                users.append(self.homeItems[1][index])
                self.homeItems[1] = users
                self.tableView.reloadSections(IndexSet(integer: 1), with: .none)
            }
        }
    }
    /// 刷新家庭信息
    func refreshHomeInfo() {
        if homeItems.count > 1 {
            loadHomeInfo(homeId: homeId) { infoData in
                self.homeItems[0] = KLMHomeItem.homeSettingHeaderItems(info: infoData, canEdit: self.canOperateHome)
                self.tableView.reloadSections(IndexSet(integer: 0), with: .none)
            }
        }
    }
    func loadHomeInfo(homeId: Int, success: @escaping (KLMHomeInfo) -> ()) {
        SVProgressHUD.show()
        KLMRequest.getHomeInfo(id: homeId) { response in
            SVProgressHUD.dismiss()
            if let infoData = response as? KLMHomeInfo {
                self.homeInfo = infoData
                success(infoData)
            }
        } failure: { error in
            SVProgressHUD.dismiss()
            self.endHeaderRefresh()
            KLMHttpShowError(error)
        }
    }
    func loadHomeUsers(homeId: Int, success: @escaping ([KLMHomeUser]) -> ()) {
        SVProgressHUD.show()
        KLMRequest.getHomeUsers(meshId: homeId) { response in
            SVProgressHUD.dismiss()
            if let userList = response as? KLMHomeUserList {
                self.homeUsers = userList.data
                success(userList.data)
            }
        } failure: { error in
            SVProgressHUD.dismiss()
            self.endHeaderRefresh()
            KLMHttpShowError(error)
        }
    }
    override func tableViewDidSelect(item: KLMHomeItem, at: IndexPath, on: UITableView) {
        super.tableViewDidSelect(item: item, at: at, on: on)
        if item.actionType == .rename {
            if !item.showArrow { return }
            /// 修改家庭名称
            let vc = KLMBaseModalController(type: .rename, operTitle: "家庭名称 ", textFieldTip: item.rightTitle, confirmTitle: KLMLocalizable.LANGLOC("Save"), confirmBlock: { [weak self] text, type in
                guard let self = self else { return }
                if type == .rename {
                    SVProgressHUD.show()
                    KLMRequest.updateHomeName(id: homeId, meshName: text!) { response in
                        SVProgressHUD.dismiss()
                        if let info = response as? KLMHomeInfo {
                            self.homeInfo = info
                        }
                        self.homeItems[at.section][at.row].rightTitle = text
                        on.reloadRows(at: [at], with: .fade)
                        
                        NotificationCenter.post(.homeNameChanged)
                    } failure: { error in
                        SVProgressHUD.dismiss()
                        KLMHttpShowError(error)
                    }
                }
            })
            modalVc(vc: vc)
        } else if item.actionType == .deleteHome {
            let action1 = UIAlertAction(title: "确定", style: .default) { _ in
                /// 删除家庭
                KLMRequest.deleteHome(id: self.homeId) { response in
                    NotificationCenter.post(.deleteHomeSuccess, userInfo: [NotificationKey.deleteHomeKey: self.homeId])
                    self.navigationController?.popViewController(animated: true)
                } failure: { error in
                    KLMHttpShowError(error)
                }
            }
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            presentActionSheet(title: "确定要删除家庭吗?", message: "家庭删除后，所有成员会被删除、数据会被清空、已添加设备会被解绑和重置", actions: [action1, cancelAction])
        } else if item.actionType == .leaveHome {
            let action1 = UIAlertAction(title: "确定", style: .default) { _ in
                /// 离开家庭
                KLMRequest.signOutHome(meshId: self.homeId, userId: self.currentUser.id) { response in
                    NotificationCenter.post(.deleteHomeSuccess, userInfo: [NotificationKey.deleteHomeKey: self.homeId])
                    self.navigationController?.popViewController(animated: true)
                } failure: { error in
                    KLMHttpShowError(error)
                }
            }
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            presentActionSheet(title: "确定要离开家庭吗?", message: "离开后，将不能操作家里设备和智能。", actions: [action1, cancelAction])
        } else if item.actionType == .addMember {
            KLMRequest.getSingleCode(meshId: homeId, username: "待加入", nickName: "新成员") { response in
                if let code = response as? String {
                    /// 添加成员
                    let text = code
                    self.presentSystemShare(
                        activityItems: [text],
                        excludedActivityTypes: [.saveToCameraRoll, .airDrop]
                    ) { completed, activityType in
                        if completed {
                            print("分享成功，类型：\(activityType?.rawValue ?? "未知")")
                            self.refreshUsers()
                        }
                    }
                }
            } failure: { error in
                KLMHttpShowError(error)
            }
        } else if item.actionType == .manageRoom {
            if !item.showArrow { return }
            /// 房间管理
            let roomVc = KLMRoomListController(homeId: homeId, operType: .manage)
            roomVc.titleText = item.title
            roomVc.popRefreshBlock = { [weak self] roomName, type, roomCount in
                guard let self = self else { return }
//                self.refreshHomeInfo()
                // 更新房间数量
                if self.homeItems.count > 0 {
                    self.homeItems[0][1].rightTitle = "\(roomCount)"
                    self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .fade)
                }
            }
            navigationController?.pushViewController(roomVc, animated: true)
        } else if item.actionType == .memberDetail {
            /// 家庭成员详情
            let detailVc = KLMHomeMemberDetailController(homeId: homeId, currentUser: currentHomeUser!, lookUser: homeUsers![at.row])
            navigationController?.pushViewController(detailVc, animated: true)
        }
    }
}
